import React from 'react'
import Component, { mapStateToProps, mapDispatchToProps } from '@components/Component'
import { connect } from 'react-redux'
import { Skeleton, message } from 'antd'
import ReactEchartsCore from 'echarts-for-react/lib/core'
import * as echarts from 'echarts/core'
import { BarChart, LineChart } from 'echarts/charts'
import { TooltipComponent } from 'echarts/components'
import { CanvasRenderer } from 'echarts/renderers'
import classnames from 'classnames'
import moment from 'moment'
import PropTypes from 'prop-types'
import style from './Week.module.less'
import { strToNum } from '@src/assets/js/tool'
echarts.use([BarChart, LineChart, CanvasRenderer, TooltipComponent])
class WeekClosure extends Component {
  state = {
    monday: Date.now(),
    nextMonday: Date.now(),
    loading: false,
    otherNum: 0,
    otherAmount: 0,
    otherFee: 0,
    otherList: [0, 0, 0, 0, 0, 0, 0],
    financeNum: 0,
    financeAmount: 0,
    financeFee: 0,
    financeList: [0, 0, 0, 0, 0, 0, 0],
    currentType: '全部'
  }

  formatMoney (money) {
    const m = String(money)
    if (!/^\d*$/.test(m)) {
      return m
    }
    return m.replace(/\B(?=(\d{3})+(?!\d))/g, ',')
  }

  // 初始化星期一和星期日的时间戳,并获取数据
  initWeekDayAndGetData () {
    const time = moment(moment().format('YYYY-MM-DD'))
    const d = time.day()
    time.subtract(d, 'd')
    const monday = Math.floor(time.valueOf() / 1000)
    time.add(6, 'd')
    time.hour(23)
    time.minute(59)
    time.second(59)
    const nextMonday = Math.floor(time.valueOf() / 1000)
    this.setState({
      monday,
      nextMonday
    }, () => {
      this.getData()
    })
  }

  // 根据案件类型获取周数据
  getWeekDataByCaseType (isOther) {
    return this.$get('/api/xapc/casestat', {
      begintime: this.state.monday,
      endtime: this.state.nextMonday,
      type: 'closure_datetime',
      group: 'date',
      field: 'caseno,amountsum,feesum',
      condition: JSON.stringify([{ k: 'casetype', o: isOther ? '<>' : '=', v: '金融案件' }])
    }).then(res => {
      const k = isOther ? 'other' : 'finance'
      if (res.status !== 1) {
        return message.warning(res.message)
      }
      const { total, list } = res.data
      this.setState({
        [`${k}List`]: list.map(li => li.caseno),
        [`${k}Num`]: total.caseno || 0,
        [`${k}Amount`]: total.amountsum || 0,
        [`${k}Fee`]: total.feesum || 0
      })
    })
  }

  // 获取数据
  getData () {
    this.setState({ loading: true })
    Promise.all([this.getWeekDataByCaseType(), this.getWeekDataByCaseType(true)])
      .then(() => { this.setState({ loading: false }) })
      .catch(() => this.setState({ loading: false }))
  }

  // 获取图表配置
  getOptions () {
    return {
      xAxis: {
        type: 'category',
        data: ['周日', '周一', '周二', '周三', '周四', '周五', '周六'],
        show: false
      },
      yAxis: {
        type: 'value',
        show: false
      },
      tooltip: {},
      series: this.getSeriesList()
    }
  }

  // 获取柱状图列表
  getSeriesList () {
    const { currentType } = this.state
    const list = []
    if (currentType === '全部') {
      list.push(this.getSeries(true, false))
      list.push(this.getSeries(false, true))
    } else if (currentType === '金融') {
      list.push(this.getSeries(false, true))
    } else {
      list.push(this.getSeries(true, true))
    }
    return list
  }

  // 获取柱状图
  getSeries (isOther, isLast) {
    const list = isOther ? this.state.otherList : this.state.financeList
    return {
      data: list.map(v => {
        const obj = {
          value: v
        }
        if (v <= 0) {
          obj.itemStyle = {
            color: '#EEEFF2',
            borderRadius: [0, 0, 0, 0]
          }
        }
        return obj
      }),
      name: isOther ? '其他案件' : '金融案件',
      type: 'bar',
      barCategoryGap: '50%',
      barMinHeight: 5,
      stack: 'total',
      color: isOther ? '#6FDDF6' : '#0039BF'
    }
  }

  // 查看详情
  chartClickHandle (e) {
    const weekList = ['周日', '周一', '周二', '周三', '周四', '周五', '周六']
    if (e.seriesType === 'bar') {
      const index = weekList.indexOf(e.name)
      const date = moment(this.state.monday * 1000)
      date.add(index, 'd')
      const meta = {
        formData: {
          beginTime: moment(date),
          endTime: moment(date),
          type: 'closure_datetime',
          casetype: e.seriesName
        }
      }
      this.props.addWindow({ id: 'AllCaseManage', title: '仲裁案件列表', componentName: 'AllCaseManage', forceRefresh: true, meta })
    }
  }

  componentDidMount () {
    this.initWeekDayAndGetData()
  }

  // 渲染总收案数
  renderTotal () {
    const { currentType, otherNum, financeNum } = this.state
    if (currentType === '金融') {
      return financeNum
    } else if (currentType === '其他') {
      return otherNum
    }
    return strToNum(financeNum) + strToNum(otherNum)
  }

  // 渲染标的
  renderAmount () {
    const { currentType, otherAmount, financeAmount } = this.state
    if (currentType === '金融') {
      return financeAmount
    } else if (currentType === '其他') {
      return otherAmount
    }
    return strToNum(financeAmount) + strToNum(otherAmount)
  }

  // 渲染费用
  renderFee () {
    const { currentType, otherFee, financeFee } = this.state
    if (currentType === '金融') {
      return financeFee
    } else if (currentType === '其他') {
      return otherFee
    }
    return strToNum(financeFee) + strToNum(otherFee)
  }

  // 渲染类型列表
  renderTypes () {
    const c = this.state.currentType
    const list = ['全部', '金融', '其他']
    return list.map(li => {
      const names = classnames(style['header-type__li'], { [style.active]: c === li })
      return <span key={li} className={names} onClick={() => this.setState({ currentType: li })}>{li}</span>
    })
  }

  render () {
    const { loading } = this.state
    const onEvents = { click: this.chartClickHandle.bind(this) }
    return (
      <div className={style['header-block']}>
        <Skeleton active loading={loading}>
          <div className={style['header-block__cell']}>
            <div className={style['header-block__cell--left']}>
              <div className={style.title}>周实时结案</div>
              <div className={style.num}>{this.renderTotal()}</div>
              <div className={style.chart}>
                <ReactEchartsCore className={classnames({ [style.hide]: !this.props.ready })} echarts={echarts} option={this.getOptions()} onEvents={onEvents} style={{ width: '100%', height: '100%' }} />
              </div>
            </div>
          </div>
          <div className={style['header-block__cell']}>
            <div className={style['header-block__cell--right']}>
              {/* <div className={style['header-type__list']}>
                {this.renderTypes()}
              </div> */}
              <div className={style.cell}>
                <div className={style.title}>标的</div>
                <div className={style.money}>￥{this.formatMoney(this.renderAmount())}</div>
              </div>
              <div className={style.cell}>
                <div className={style.title}>仲裁费</div>
                <div className={style.money}>￥{this.formatMoney(this.renderFee())}</div>
              </div>
            </div>
          </div>
        </Skeleton>
      </div>
    )
  }
}

WeekClosure.propTypes = {
  ready: PropTypes.bool
}

WeekClosure.defaultProps = {
  ready: false
}

const mapState = mapStateToProps(function (state) {
  return {
    uncompleteNum: state.basic.uncompleteNum
  }
})

const mapDispatch = mapDispatchToProps(function (dispatch) {
  return {

  }
})

export default connect(mapState, mapDispatch)(WeekClosure)
